package com.sui.bigdata.rtcadmin.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author YongChen
 * @date 2019/12/30 11:15
 * @description
 * @email yong_chen@sui.com
 */

@Component
public class RedisUtils {

    private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    public boolean setScheduler(final String key, String value) {

        boolean result = false;
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value,10,TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("redis error: ",e);
        }
        return result;
    }

    public boolean setScheduler(final String key, String value,long timeout) {

        boolean result = false;
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value,timeout,TimeUnit.SECONDS);
        } catch (Exception e) {
           logger.error("redis error: ",e);
        }
        return result;
    }

    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    public Integer getInteger(String key) {
        if (key == null){
            return null;
        }else {
            Object object = redisTemplate.opsForValue().get(key);
            if (null == object){
                return 0;
            }else {
                return  Integer.valueOf(String.valueOf(object));
            }
        }
    }

    public Boolean getBoolean(String key) {
        if (key == null){
            return Boolean.FALSE;
        }else {
            Object object = redisTemplate.opsForValue().get(key);
            if (null == object){
                return Boolean.FALSE;
            }else {
                return Boolean.valueOf(String.valueOf(object));
            }
        }
    }

    public void set(String key,String value,Long ttl) {
       redisTemplate.opsForValue().set(key,value,ttl,TimeUnit.SECONDS);
    }

    public void set(String key,int value,Long ttl) {
        redisTemplate.opsForValue().set(key,value,ttl,TimeUnit.SECONDS);
    }

    public void set(String key,String value) {
        redisTemplate.opsForValue().set(key,value);
    }

    public void remove(String key,String lockValue) {
        if (key == null || lockValue == null){
            return;
        }
        try {
            if (lockValue.equals(redisTemplate.opsForValue().get(key))) {
                redisTemplate.delete(key);
            }
        }catch (Exception e){
            logger.error("alarm task ,remove {} error!",key);
        }
    }
}



